<?php
declare (strict_types = 1);

namespace app\controller;

use app\common\BaseController;
use app\service\ShowService;
use think\facade\Validate;
use app\service\OrderService;
use think\Request;

class ShowController extends BaseController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index(Request $request)
    {
      $page = $request->param('page', 1);
      $pageSize = $request->param('pageSize', 10);
      $customer = $request->param('customer', '');
      $model = $request->param('model', '');
      $states = $request->param('states', '');
      $conditions = [];
      if ($customer) {
        $customer = trim($customer);
        $conditions[] = ['customer', "%{$customer}%", 'like'];
      }
      if ($states !== '') {
        $conditions[] = ['states', $states, '='];
      }
      if ($model) {
        $conditions[] = ['model', "%{$model}%", 'like'];
      }
      $order = ['date' => 'desc', 'oid' => 'desc', 'id' => 'desc'];
      $res = ShowService::getInstance()->getAllShow($conditions,$order);
      if ($customer || $model || $states) {
        $oids = array_unique(array_column($res, 'oid'));
        $list = ShowService::getInstance()->getAllShow([['oid', $oids, 'IN']],$order);
      } else {
        $list = $res;
      }
      // 分组标识 date-oid-customer
      $data = [];
      foreach ($list as $value) {
        $str = $value['date'].'-'.$value['oid'].'-'.$value['customer'];
        if (isset($data[$str])) {
          $data[$str]['children'][] = [
            'id' => $value['id'],
            'state' => $value['state'],
            'product' => $value['product'],
            'productn' => $value['productn'],
            'model' => $value['model'],
            'cost' => $value['cost'],
            'amoumt' => $value['amoumt'],
            'other' => $value['other'],
            'states' => $value['states'],
            'backtime' => $value['backtime'],
            'new' => $value['new'],
            'unit' => $value['unit'],
            'price' => $value['price'],
            'discount' => $value['discount'],
            'tprice' => $value['tprice'],
            'paid' => $value['paid']
          ];
        } else {
          $data[$str] = $value;
          $item['hasChildren'] = false;
        }
      }
      $data = array_values($data);
      $index = 1;
      $color = true;
      // 进行新增数据
      foreach ($data as &$item) {
        $amoumt = [];
        $tprice = [];
        $item['index'] = $index++;
        $item['color'] = $color ? 'green' : 'blue';
        $item['hasChildren'] = false;
        $item['ischild'] = false;
        // 获取打印数据
        $print = [
          'customer' => $item['customer'],
          'address' => $item['address'],
          'cname' => $item['cname'],
          'phone' => $item['phone'],
          'installtime' => $item['installtime'],
          'itime' => $item['itime'],
          'children' => [
            [
              'productn' => $item['productn'],
              'model' => $item['model'],
              'unit' => $item['unit'],
              'amoumt' => $item['amoumt'],
              'price' => $item['price'],
              'discount' => $item['discount'],
              'tprice' => $item['tprice'],
              'other' => $item['other']
            ]
          ]
        ];
        // 新增数据
        $add = [
          'oid' => $item['oid'],
          'date' => $item['date'],
          'customer' => $item['customer'],
          'address' => $item['address'],
          'new' => $item['new'],
          'states' => $item['states'],
          'cname' => $item['cname'],
          'phone' => $item['phone'],
          'installtime' => $item['installtime'],
          'itime' => $item['itime']
        ];
        if (isset($item['children'])) {
          foreach ($item['children'] as &$child) {
            $item['hasChildren'] = true;
            $child['index'] = $index++;
            $child['ischild'] = true;
            $child['color'] = $color ? 'green' : 'blue';
            $print['children'][] = [
              'productn' => $child['productn'],
              'model' => $child['model'],
              'unit' => $child['unit'],
              'amoumt' => $child['amoumt'],
              'price' => $child['price'],
              'discount' => $child['discount'],
              'tprice' => $child['tprice'],
              'other' => $child['other']
            ];
          }
        }
        $print['total'] = [
          'tprice' => array_sum($tprice) + $item['tprice'],
          'amoumt' => array_sum($amoumt) + $item['amoumt']
        ];
        $item['print'] = $print;
        $item['add'] = $add;
        $color = !$color;
      }
      // 分页
      $count = count($data); //总条数
      $start=($page-1) * $pageSize; //偏移量，当前页-1乘以每页显示条数
      $pager = [
        'totalRecord' => $count * 1,
        'pageSize' => $pageSize * 1,
        'currPage' => $page * 1,
        'totalPage' => intval($count/$pageSize)+1
      ];
      $list = array_slice($data,$start,$pageSize*1);
      return $this->send200ResponseWithPager($list, $pager);
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
      $data = $request->param('data', []);
      $validate = Validate::rule([
        'date' => 'require',
        'customer' => 'require',
        'address' => 'require',
        'cname' => 'require',
        'phone' => 'require',
        'product' => 'require',
        'productn' => 'require',
        'new' => 'require',
        'amoumt' => 'require',
        'state' => 'require',
        'model' => 'require',
        'states' => 'require'
      ]);
      if (!$validate->check($data)) {
        return $this->send400Response($validate->getError());
      }
      $res = ShowService::getInstance()->createShow($data);
      if (!$res['status']) {
        return $this->send400Response($res['msg']);
      }
      return $this->send200Response('ok');
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
      $data = ShowService::getModel()->find($id);
      return $this->send200Response($data);
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
      $showForm = $request->param('showForm', []);
      $updateForm = $request->param('updateForm', []);
      $showValid = Validate::rule([
        'date' => 'require',
        'customer' => 'require',
        'address' => 'require',
        'cname' => 'require',
        'phone' => 'require'
      ]);
      $updateValid = Validate::rule([
        'state' => 'require',
        'states' => 'require'
      ]);
      // 判断订单数据
      if (!$showValid->check($showForm)) {
        return $this->send400Response($showValid->getError());
      }
      // 判断数据
      if (!$updateValid->check($updateForm)) {
        return $this->send400Response($updateValid->getError());
      }
      $data = [
        'showForm' => $showForm,
        'updateForm' => $updateForm,
      ];
      $res = ShowService::getInstance()->updateShow($id, $data);
      if (!$res['status']) {
        return $this->send400Response($res['msg']);
      }
      return $this->send200Response('ok');
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
      $res = ShowService::getInstance()->deleteShow($id);
      if (!$res['status']) {
        return $this->send400Response($res['msg']);
      }
      return $this->send200Response('ok');
    }

    /**
     * 购买
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function purchase(Request $request)
    {
      $data = $request->param('data', []);
      $validate = Validate::rule([
        'date' => 'require',
        'customer' => 'require',
        'address' => 'require',
        'cname' => 'require',
        'phone' => 'require',
        'product' => 'require',
        'productn' => 'require',
        'model' => 'require',
        'price' => 'require',
        'amoumt' => 'require',
        'discount' => 'require',
        'paid' => 'require',
        'invoice' => 'require',
        'tax' => 'require',
        'js' => 'require',
        'id' => 'require'
      ]);
      if (!$validate->check($data)) {
        return $this->send400Response($validate->getError());
      }
      $res = OrderService::getInstance()->createPurchase($data);
      if (!$res['status']) {
        return $this->send400Response($res['msg']);
      }
      return $this->send200Response('ok');
    }

    /**
     * 返仓
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function showReturn($id) {
      $res = ShowService::getInstance()->showReturn($id);
      if (!$res['status']) {
        return $this->send400Response($res['msg']);
      }
      return $this->send200Response('ok');
    }

    /**
     * 获取入库明细
     */
    public function getShowIn(Request $request) {
      $page = $request->param('page', 1);
      $pageSize = $request->param('pageSize', 10);
      $start_date = $request->param('start_date', '');
      $end_date = $request->param('end_date', '');
      $conditions = [
        ['states', [0,1,2], 'IN']
      ];
      if ($start_date) {
        $conditions[] = ['date', $start_date, '>='];
      }
      if ($end_date) {
        $conditions[] = ['date', $end_date, '<='];
      }
      // 获取展厅列表
      $data = ShowService::getInstance()->getAllShow($conditions, ['date' => 'desc', 'id' => 'desc']);
      foreach ($data as &$value) {
        $value['total'] = round($value['cost'] * $value['amoumt'], 2);
      }
      // 分页
      $count = count($data); //总条数
      $start=intval(($page - 1) * $pageSize); //偏移量，当前页-1乘以每页显示条数
      $pager = [
        'totalCount' => $count,
        'pageSize' => intval($pageSize),
        'currPage' => intval($page),
        'totalPage' => intval($count/$pageSize)+1
      ];
      $list = array_slice($data, $start, intval($pageSize));
      return $this->send200ResponseWithPager($list,$pager);
    }

    /**
     * 获取出库明细
     */
    public function getShowOut(Request $request) {
      $page = $request->param('page', 1);
      $pageSize = $request->param('pageSize', 10);
      $start_date = $request->param('start_date', '');
      $end_date = $request->param('end_date', '');
      $orderCond = [
        ['resource', 1, '=']
      ];
      if ($start_date) {
        $orderCond[] = ['date', $start_date, '>='];
      }
      if ($end_date) {
        $orderCond[] = ['date', $end_date, '<='];
      }
      $data = [];
      // 获取展厅购买列表
      $order = OrderService::getInstance()->getAllOrder($orderCond, ['date' => 'desc', 'id' => 'desc']);
      foreach ($order as $oValue) {
        $data[] = [
          'date' => $oValue['date'],
          'type' => 1,
          'product' => $oValue['product'],
          'productn' => $oValue['productn'],
          'model' => $oValue['model'],
          'amoumt' => $oValue['amoumt'],
          'unit' => $oValue['unit'],
          'cost' => $oValue['cost'],
          'price' => $oValue['price'],
          'cost_total' => round($oValue['cost'] * $oValue['amoumt'], 2),
          'price_total' => round($oValue['price'] * $oValue['amoumt'], 2),
          'outtime' => $oValue['sendtime'],
          'datesort' => strtotime($oValue['date'])
        ];
      }
      // 获取展厅返仓
      $showCon = [
        ['states', 0, '=']
      ];
      if ($start_date) {
        $showCon[] = ['backtime', $start_date, '>='];
      }
      if ($end_date) {
        $showCon[] = ['backtime', $end_date, '<='];
      }
      $showList = ShowService::getInstance()->getAllShow($showCon, ['date' => 'desc', 'id' => 'desc']);
      foreach ($showList as $sValue) {
        $data[] = [
          'date' => $sValue['date'],
          'type' => 2,
          'product' => $sValue['product'],
          'productn' => $sValue['productn'],
          'model' => $sValue['model'],
          'amoumt' => $sValue['amoumt'],
          'unit' => $sValue['unit'],
          'cost' => $sValue['cost'],
          'price' => $sValue['price'],
          'cost_total' => round($sValue['cost'] * $sValue['amoumt'], 2),
          'price_total' => round($sValue['price'] * $sValue['amoumt'], 2),
          'outtime' => $sValue['backtime'],
          'datesort' => $sValue['backtime'] ? strtotime($sValue['backtime']) : ''
        ];
      }
      // 排序
      $dateSort = [];
      $typeSort = [];
      foreach ($data as $key=>$value){
        $dateSort[$key] = $value['datesort'];
        $typeSort[$key] = $value['type'];
      }
      if ($dateSort && $data && $typeSort) {
        array_multisort($dateSort,SORT_NUMERIC,SORT_DESC, $typeSort,SORT_NUMERIC,SORT_ASC, $data);
      }

      // 分页
      $count = count($data); //总条数
      $start=intval(($page - 1) * $pageSize); //偏移量，当前页-1乘以每页显示条数
      $pager = [
        'totalCount' => $count,
        'pageSize' => intval($pageSize),
        'currPage' => intval($page),
        'totalPage' => intval($count/$pageSize)+1
      ];

      $list = array_slice($data, $start, intval($pageSize));
      return $this->send200ResponseWithPager($list,$pager);

    }
}
